package com.example.demo.heima.netty.client;

import com.example.demo.heima.netty.server.TcpStickHalfHandler1;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.charset.StandardCharsets;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname NettyClient
 * @description
 * @date 2023/07/21 22:26
 * <p>
 * ******************************************************
 */
public class NettyClient {

    public static void main(String[] args) {
        NettyClient client = new NettyClient();
        client.connect("127.0.0.1", 8888);
    }

    private void connect(String ip, int port) {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    // pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                     pipeline.addLast(new NettyClientInBoundHandler1());

                    pipeline.addLast(new LengthFieldBasedFrameDecoder(65535, 0, 4,0, 4));

                    pipeline.addFirst(new LengthFieldPrepender(4));
                }
            });

            ChannelFuture future = bootstrap.connect(ip, port).sync();
            Channel channel = future.channel();
            // 向服务端写数据
            // ByteBuf buffer = channel.alloc().buffer();
            // buffer.writeBytes("hello nioserver".getBytes(StandardCharsets.UTF_8));
            // channel.writeAndFlush(buffer);

            // 等待端口断开
            channel.closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }

    }
}
